package com.filetransfer.app.ui.dashboard

import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.filetransfer.app.databinding.FragmentDashboardBinding
import com.filetransfer.app.db.HistoryDatabaseHelper
import com.filetransfer.app.db.HistoryDatabaseHelper.History

class DashboardFragment : Fragment() {
    private var _binding: FragmentDashboardBinding? = null
    private val binding get() = _binding!!
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        val dashboardViewModel =
            ViewModelProvider(this).get(DashboardViewModel::class.java)
        _binding = FragmentDashboardBinding.inflate(inflater, container, false)
        val root: View = binding.root
        // 初始化 RecyclerView
        val recyclerView: RecyclerView = binding.recyclerView
        recyclerView.layoutManager = LinearLayoutManager(context)
        context?.let { refreshItems(it) }
        return root
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    private fun refreshItems(context: Context) {
        try {
            val db: HistoryDatabaseHelper = HistoryDatabaseHelper(context)
            db.use {
                val sampleData = ArrayList<History>()
                for (history in db.queryAll().reversed()) {
                    sampleData.add(history);
                }
                val adapter = UploadHistoryAdapter(sampleData)
                binding.recyclerView.adapter = adapter
            }
        } catch (e: Exception) {
//            val db: HistoryDatabaseHelper = HistoryDatabaseHelper(context)
//            db.use {
//                db.deleteAll()
//            }
//            e.printStackTrace()
        }
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        refreshItems(context)
    }
}
